package com.kk.handlers;

import com.kk.utils.JwtUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.math.BigInteger;
import java.util.Map;

/**
 * @author kl
 * @version 1.0
 * @description: TODO
 * @date 2025/10/15 下午5:22
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    private final JwtUtil jwtUtil;
    private final UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(
            @NonNull HttpServletRequest request,
            @NonNull HttpServletResponse response,
            @NonNull FilterChain filterChain) throws ServletException, IOException {

        try {
            // 1. 从请求头中获取token
            String token = getTokenFromRequest(request);

            // 2. 如果token存在且有效，则进行认证
            if (StringUtils.hasText(token) && JwtUtil.verify(token)) {
                // 3. 从token中获取用户名
                String username = JwtUtil.getUsername(token);

                // 4. 如果用户名存在且当前SecurityContext中没有认证信息
                if (StringUtils.hasText(username) && SecurityContextHolder.getContext().getAuthentication() == null) {
                    // 5. 加载用户详情
                    UserDetails userDetails = userDetailsService.loadUserByUsername(username);

                    // 6. 验证token是否与用户匹配
                    if (JwtUtil.verify(token, username)) {
                        // 7. 创建认证对象
                        UsernamePasswordAuthenticationToken authentication =
                                new UsernamePasswordAuthenticationToken(
                                        userDetails,
                                        null,
                                        userDetails.getAuthorities()
                                );

                        // 8. 从token中提取用户ID并设置到details中
                        authentication.setDetails(
                                new WebAuthenticationDetailsSource().buildDetails(request)
                        );

                        // 9. 将认证信息设置到SecurityContext中
                        SecurityContextHolder.getContext().setAuthentication(authentication);

                        log.debug("✅ JWT认证成功: username={}", username);
                    }
                }
            }
        } catch (Exception e) {
            log.error("JWT认证过程发生异常", e);
            // 不抛出异常，让请求继续，由Spring Security的其他机制处理
        }

        // 10. 继续执行过滤器链
        filterChain.doFilter(request, response);
    }

    private String getTokenFromRequest(HttpServletRequest request) {
        // 此时是带有前缀的
        String tokens = request.getHeader(jwtUtil.getHeader());
        if(StringUtils.hasText(tokens)){
            return jwtUtil.getTokenFromHeader(tokens);
        }
        // 避免token放在其它地方
        String token = request.getHeader("token");
        if(StringUtils.hasText(token)){
            return token;
        }
        // 可能token在参数里面（大多数不会这么做，但是预防）
        return request.getParameter("token");
    }

    /**
     * 从JWT token中提取用户ID
     */
    private BigInteger extractUserIdFromToken(String token) {
        try {
            Map<String, Object> claims = JwtUtil.parse(token);
            Object idObj = claims.get("id");

            if (idObj instanceof BigInteger) {
                return (BigInteger) idObj;
            } else if (idObj instanceof Number) {
                return BigInteger.valueOf(((Number) idObj).longValue());
            } else if (idObj instanceof String) {
                return new BigInteger((String) idObj);
            }
        } catch (Exception e) {
            log.warn("从token中提取用户ID失败", e);
        }
        return null;
    }

}
